package com.supermarket_project.utils;

import org.krysalis.barcode4j.impl.code128.Code128Bean;
import org.krysalis.barcode4j.impl.upcean.EAN8Bean;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

/**
 * 生成条形码类
 */
public class BarCodeUtil {

    /**
     * 具体实现
     *
     * @param msg  要生成条形码的信息，比如id
     * @param path 输出路径
     */
    public int getBarCode(String msg, String path) {
        try {
            File file = new File(path);
            OutputStream ous = new FileOutputStream(file);
            if (msg.equals(null) || ous == null)
                return -1;
            //选择条形码类型(好多类型可供选择)
            //EAN8Bean bean=new EAN8Bean();商品常用条形码类型
            Code128Bean bean = new Code128Bean();
            //设置长宽
            final double moduleWidth = 0.20;
            final int resolution = 150;
            bean.setModuleWidth(moduleWidth);
            bean.doQuietZone(false);
            String format = "image/png";
            // 输出流
            BitmapCanvasProvider canvas = new BitmapCanvasProvider(ous, format,
                    resolution, BufferedImage.TYPE_BYTE_BINARY, false, 0);
            //生成条码
            bean.generateBarcode(canvas, msg);
            canvas.finish();
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }

    }

    public static void main(String[] args) {

        String msg = "pillar666";
        String path = "D:\\mybarcode\\pilar666.jpg";
        BarCodeUtil barCodeUtil = new BarCodeUtil();
        barCodeUtil.getBarCode(msg, path);
    }
}
